#include <stdio.h>
#include <assert.h>
#include "glory.h"

void disp(void *cls);
void reshape(int x, int y, void *cls);
void keyb(int key, int state, void *cls);
void mouse(int bn, int state, int x, int y, void *cls);
void motion(int x, int y, void *cls);

int mouse_x = 10, mouse_y = 10;

int main(void)
{
	glory_init();
	glory_create_window(800, 600, GLORY_DEPTH | GLORY_DOUBLE);

	glory_display_callback(disp, 0);
	glory_reshape_callback(reshape, 0);
	glory_keyboard_callback(keyb, 0);
	glory_mouse_callback(mouse, 0);
	glory_motion_callback(motion, 0);
	glory_passive_callback(motion, 0);

	glory_event_loop();
	return 0;
}


void disp(void *cls)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(mouse_x, mouse_y, 0);

	glRotatef(45, 0, 0, 1);
	glScalef(20, 20, 20);

	glBegin(GL_TRIANGLES);
	glColor3f(1, 0, 0);
	glVertex2f(0, 0);
	glColor3f(0.5, 0.1, 0.05);
	glVertex2f(0.3, 1);
	glVertex2f(-0.3, 1);

	glColor3f(1, 0, 0);
	glVertex2f(0, 0);
	glColor3f(0.5, 0.1, 0.05);
	glVertex2f(-0.3, -1);
	glVertex2f(0.3, -1);

	glColor3f(1, 0, 0);
	glVertex2f(0, 0);
	glColor3f(0.5, 0.1, 0.05);
	glVertex2f(-1, 0.3);
	glVertex2f(-1, -0.3);

	glColor3f(1, 0, 0);
	glVertex2f(0, 0);
	glColor3f(0.5, 0.1, 0.05);
	glVertex2f(1, -0.3);
	glVertex2f(1, 0.3);
	glEnd();

	glory_swap_buffers();

	assert(glGetError() == GL_NO_ERROR);
}

void reshape(int x, int y, void *cls)
{
	glViewport(0, 0, x, y);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, x, y, 0, -1, 1);
}

void keyb(int key, int state, void *cls)
{
	switch(key) {
	case 27:
		glory_quit();
		break;
	}
}

void mouse(int bn, int state, int x, int y, void *cls)
{
	if(bn == 0) {
		if(state) {
			glClearColor(0.1, 0.2, 0.6, 1);
		} else {
			glClearColor(0, 0, 0, 1);
		}
		glory_redisplay();
	}
}

void motion(int x, int y, void *cls)
{
	mouse_x = x;
	mouse_y = y;

	glory_redisplay();
}
